﻿using RayD.Repository;
using System.Collections.Generic;
using System.Text;
using RayD.Repository.Entites.SystemModule;
using RayD.Core;
using System.Linq;
using System;

namespace RayD.App.SystemModule
{
    public class AuthorizeApp
    {
        #region 构造函数注入
        private IRepository BaseRepository;
        public AuthorizeApp(IRepository repository)
        {
            this.BaseRepository = repository;
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 获取授权功能主键集合
        /// </summary>
        /// <param name="objectId">对象主键（角色,用户）</param>
        /// <param name="itemType">项目类型:1-菜单2-按钮3-视图</param>
        /// <returns></returns>
        [Caching]
        public virtual List<string> GetItemIdList(string objectId, int itemType)
        {
            var expression = LinqExtensions
                .True<AuthorizeEntity>()
                .And(c => c.B_ObjectId == objectId)
                .And(c => c.B_ItemType == itemType);
            return BaseRepository
                .IQueryable(expression)
                .Select(c => c.B_ItemId)
                .ToList();
        }

        /// <summary>
        /// 获取权限模块功能列表数据
        /// </summary>
        /// <param name="account">登录账户（记缓存）</param>
        /// <returns></returns>
        [Caching]
        public virtual List<ModuleEntity> GetAuthorizeModuleList(string account)
        {
            StringBuilder strSql = new StringBuilder(200);

            /*关联权限*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                strSql.Append(@" Select 
                                B_ModuleId
                               ,B_ParentId
                               ,B_EnCode
                               ,B_FullName
                               ,B_Icon
                               ,B_UrlAddress
                               ,B_SortCode
                               ,B_EnabledMark
                               ,B_Description
                               ,B_CreateDate
                               ,B_CreateUserId
                               ,B_CreateUserName
                               ,B_ModifyDate
                               ,B_ModifyUserId
                               ,B_ModifyUserName
                             FROM BASE_MODULE 
WHERE B_ModuleId IN
(
	SELECT B_ItemId FROM BASE_AUTHORIZE
	WHERE B_ItemType = 1
    AND B_ObjectId IN ( {0} )
)
AND B_EnabledMark = 1
Order By B_SortCode 
");
                string objectIds = userInfo.userId + (string.IsNullOrEmpty(userInfo.roleIds) ? "" : ("," + userInfo.roleIds)) + (string.IsNullOrEmpty(userInfo.postIds) ? "" : ("," + userInfo.postIds));
                objectIds = "'" + objectIds.Replace(",", "','") + "'";
                return BaseRepository.FindList<ModuleEntity>(string.Format(strSql.ToString(), objectIds)).ToList();
            }
            else
            {
                return BaseRepository
                    .IQueryable(LinqExtensions.True<ModuleEntity>().And(c => c.B_EnabledMark == EnabledMark.Enabled))
                    .OrderBy(c => c.B_SortCode)
                    .ToList();
            }

        }
        /// <summary>
        /// 获取权限按钮列表数据
        /// </summary>
        /// <param name="account">登录账户（记缓存）</param>
        /// <param name="moduleId">模块功能Id</param>
        /// <returns></returns>
        [Caching]
        public virtual List<ModuleButtonEntity> GetAuthorizeButtonList(string account, string moduleId = "")
        {

            StringBuilder strSql = new StringBuilder(200);

            /*关联权限*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                strSql.Append(@" Select 
                                B_ModuleButtonId
                                ,B_ModuleId
                                ,B_Encode
                                ,B_FullName
                                ,B_SortCode
                             From BASE_MODULEBUTTON
WHERE B_ModuleButtonId IN
(
	SELECT B_ItemId FROM BASE_AUTHORIZE
	WHERE B_ItemType = 2
    AND B_ObjectId IN ( {0} )
)");
                if (!moduleId.IsEmpty())
                {
                    strSql.Append($" AND B_ModuleId = '{moduleId}' ");
                }
                strSql.Append(" Order By B_SortCode ");

                string objectIds = userInfo.userId + (string.IsNullOrEmpty(userInfo.roleIds) ? "" : ("," + userInfo.roleIds)) + (string.IsNullOrEmpty(userInfo.postIds) ? "" : ("," + userInfo.postIds));
                objectIds = "'" + objectIds.Replace(",", "','") + "'";
                return BaseRepository.FindList<ModuleButtonEntity>(string.Format(strSql.ToString(), objectIds)).ToList();
            }
            else
            {
                var expression = LinqExtensions.True<ModuleButtonEntity>();
                if (!moduleId.IsEmpty())
                {
                    expression = expression.And(c => c.B_ModuleId == moduleId);
                }
                return BaseRepository
                    .IQueryable(expression)
                    .OrderBy(c => c.B_SortCode)
                    .ToList();
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 添加授权
        /// </summary>
        /// <param name="objectType">权限分类-1角色2用户3岗位</param>
        /// <param name="objectId">对象Id</param>
        /// <param name="moduleIds">功能Id</param>
        /// <param name="moduleButtonIds">按钮Id</param>
        [RemoveCache]
        public virtual (bool, string) SaveAuthorize(int objectType, string objectId, string[] moduleIds, string[] moduleButtonIds)
        {
            IRepository db = this.BaseRepository.BeginTrans();
            try
            {
                db.Delete<AuthorizeEntity>(t => t.B_ObjectId == objectId);

                List<AuthorizeEntity> authorizeEntitys = new List<AuthorizeEntity>();
                #region 功能
                foreach (string item in moduleIds)
                {
                    AuthorizeEntity entity = new AuthorizeEntity()
                    {
                        B_ObjectType = objectType,
                        B_ObjectId = objectId,
                        B_ItemType = 1,
                        B_ItemId = item
                    };
                    entity.Create();
                    authorizeEntitys.Add(entity);
                }
                #endregion

                #region 按钮
                foreach (string item in moduleButtonIds)
                {
                    AuthorizeEntity entity = new AuthorizeEntity()
                    {
                        B_ObjectType = objectType,
                        B_ObjectId = objectId,
                        B_ItemType = 2,
                        B_ItemId = item
                    };
                    entity.Create();
                    authorizeEntitys.Add(entity);
                }
                #endregion
                db.Insert(authorizeEntitys);

                db.Commit();
                return (true, "保存成功！");
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
        }

        #endregion

        #region 扩展操作

        #endregion

    }
}
